import React, { useRef, useState, useEffect } from 'react';
import Cropper from 'cropperjs';
import 'cropperjs/dist/cropper.css';

interface ImageCropperProps {
    imageUrl: string;
}

const ImageCropper: React.FC<ImageCropperProps> = ({ imageUrl }) => {
    const imageRef = useRef<HTMLImageElement>(null);
    const cropperRef = useRef<Cropper | null>(null);
    const [isCropperVisible, setIsCropperVisible] = useState(false);
    const [croppedImageUrl, setCroppedImageUrl] = useState<string | null>(null);

    useEffect(() => {
        if (imageRef.current && isCropperVisible) {
            cropperRef.current = new Cropper(imageRef.current, {
                aspectRatio: 16 / 9,
                viewMode: 1,
                dragMode: 'crop',
                cropBoxMovable: true,
                cropBoxResizable: true,
                background: false,
                autoCropArea: 1,
                guides: true,
                highlight: true,
                restore: true, 
            });

            return () => {
                cropperRef.current?.destroy();
            };
        }
    }, [isCropperVisible, imageUrl]);

    const handleImageClick = () => {
        setIsCropperVisible(true);
    };

    const handleCropDone = () => {
        const croppedCanvas = cropperRef.current?.getCroppedCanvas();
        if (croppedCanvas) {
            const croppedImageUrl = croppedCanvas.toDataURL();
            setCroppedImageUrl(croppedImageUrl);
        }
        setIsCropperVisible(false);
    };
    
    return (
        <div>
            <img
                ref={imageRef}
                src={croppedImageUrl || imageUrl}
                alt="Sample"
                onClick={handleImageClick}
            />
            {isCropperVisible && (
                <div style={{ position: 'relative' }}>
                    <button
                        onClick={handleCropDone}
                        style={{
                            position: 'absolute',
                            top: '10px',
                            right: '10px',
                            zIndex: 1001,
                        }}
                    >
                        完成
                    </button>
                </div>
            )}
        </div>
    );
};

export default ImageCropper;